package com.gjy.design.single;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * 序列化破坏单例
 * 实现 readResolve 方法可以使反序列化后的对象前后保持一致
 *
 * @author gjy
 * @version 1.0
 * @since 2025-11-06 10:15:09
 */
public class SingletonBreakerBySerialization {
    private static final Logger log = LoggerFactory.getLogger(SingletonBreakerBySerialization.class);

    public static void main(String[] args) {
        // 准备一个可序列化的单例（这里用DCL作为示例）
        DCLSingleton instance1 = DCLSingleton.getInstance();
        log.info("原始实例的 hashCode: {}", instance1.hashCode());

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        // 将实例序列化到文件
        try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(instance1);
            log.info("序列化成功！");
        } catch (IOException e) {
            log.error("序列化过程中发生异常", e);
        }

        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        // 从文件反序列化
        try (ObjectInputStream ois = new ObjectInputStream(bis)) {
            DCLSingleton instance2 = (DCLSingleton) ois.readObject();
            log.info("反序列化后的实例 hashCode: {}", instance2.hashCode());

            // 比较两个实例
            log.info("两个实例是否相同: {}", (instance1 == instance2));
        } catch (IOException | ClassNotFoundException e) {
            log.error("反序列化过程中发生异常", e);
        }
    }

}
